﻿using ClosedXML.Excel;
using CommonServiceLocator;
using Communication;
using DocumentFormat.OpenXml.InkML;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using HandyControl.Controls;
using Jn698._45GWTool.Communication;
using Jn698._45GWTool.Models;
using Jn698._45GWTool.Models.DataGrid;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using WebFirst.Entities;


using static Communication.MessageGenerationModule;
using MessageBox = System.Windows.MessageBox;

namespace Jn698._45GWTool.ViewModels.Controls
{
    public class SpecialRecordViewModel:ViewModelBase
    {
        private SendModule SendModule = new SendModule();
        public SpecialRecordViewModel()
        {
			TypeList = new List<string>() { "档案","任务","方案"};
            MeterInfoLIst = new ObservableCollection<MeterInfo>();
            PlanInfoList = new ObservableCollection<PlanInfo>();
            JobInfoList = new ObservableCollection<JobInfo>();
            TypeIndex = 0;
           
        }

        private int typeIndex;

		public int TypeIndex
		{
			get { return typeIndex; }
			set { typeIndex = value; RaisePropertyChanged(); SetZIndex(value); }
		}

		private List<string> typeList;

		public List<string> TypeList
		{
			get { return typeList; }
			set { typeList = value; RaisePropertyChanged(); }
		}

		private ObservableCollection<MeterInfo> meterInfoLIst;

		public ObservableCollection<MeterInfo> MeterInfoLIst
        {
			get { return meterInfoLIst; }
			set { meterInfoLIst = value; RaisePropertyChanged(); }
		}

        private ObservableCollection<JobInfo> jobInfoList;

        public ObservableCollection<JobInfo> JobInfoList
        {
            get { return jobInfoList; }
            set { jobInfoList = value; RaisePropertyChanged(); }
        }

        private ObservableCollection<PlanInfo> planInfoList;

        public ObservableCollection<PlanInfo> PlanInfoList
        {
            get { return planInfoList; }
            set { planInfoList = value; RaisePropertyChanged(); }
        }


		private bool meterInfoDataGridtVisibility;

		public bool MeterInfoDataGridtVisibility
        {
			get { return meterInfoDataGridtVisibility; }
			set { meterInfoDataGridtVisibility = value; RaisePropertyChanged(); }
		}

        private bool planInfoDataGridtVisibility;

        public bool PlanInfoDataGridtVisibility
        {
            get { return planInfoDataGridtVisibility; }
            set { planInfoDataGridtVisibility = value; RaisePropertyChanged(); }
        }

        private bool jobInfoDataGridtVisibility;

        public bool JobInfoDataGridtVisibility
        {
            get { return jobInfoDataGridtVisibility; }
            set { jobInfoDataGridtVisibility = value; RaisePropertyChanged(); }
        }

        private bool exportBtnVisibility;
        public bool ExportBtnVisibility
        {
            get { return exportBtnVisibility; }
            set { exportBtnVisibility = value; RaisePropertyChanged(); }
        }

        private void SetZIndex(int zIndexName)
        {
            MeterInfoDataGridtVisibility = false;
            PlanInfoDataGridtVisibility = false;
            JobInfoDataGridtVisibility = false;
            ExportBtnVisibility = false;
            switch (TypeList[zIndexName])
            {
                case "档案":
                    MeterInfoDataGridtVisibility = true;
                    ExportBtnVisibility = true;
                    break;
                case "方案":
                    PlanInfoDataGridtVisibility = true;
                    break;
                case "任务":
                    JobInfoDataGridtVisibility = true;
                    break;
                default:
                    break;
            }
        }

        public async Task ReadTask()
        {
           
            await Task.Run(async () =>
            {
                
                List<string> strings = new List<string>();
                switch (typeList[typeIndex])
                {
                    case "档案":
                        Application.Current.Dispatcher.Invoke(() => { MeterInfoLIst.Clear(); });
                        strings.Add("60000200");
                        break;
                    case "任务":
                        Application.Current.Dispatcher.Invoke(() => { JobInfoList.Clear(); });
                        strings.Add("60120200");
                        break;
                    case "方案":
                        Application.Current.Dispatcher.Invoke(() => { PlanInfoList.Clear(); });
                        strings.Add("60140200");
                        break;
                    default:
                        break;
                }
                SendModule.SecuritySelectedIndex = ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex;
                switch (SendModule.SecuritySelectedIndex)
                {

                    //明文+RN_MAC
                    case 2:
                    //明文+SID_MAC
                    case 3:
                    //密文+SID
                    case 4:
                    //密文+SID_MAC
                    case 5:
                        if (string.IsNullOrWhiteSpace(SendModule.SessionInitKey))
                        {
                            MessageBox.Show("请先建立应用连接");
                            return;
                        }
                        break;
                    //明文
                    case 0:
                    //明文+RN
                    case 1:
                    default:

                        break;
                }
                await SendModule.ReadRequest(ReadMode.GetRequestNormal, strings, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
            });
        }

        public async Task ReadNextTask()
        {
            SendModule.SecuritySelectedIndex = ServiceLocator.Current.GetInstance<MainViewModel>().SecuritySelectedIndex;
            switch (SendModule.SecuritySelectedIndex)
            {

                //明文+RN_MAC
                case 2:
                //明文+SID_MAC
                case 3:
                //密文+SID
                case 4:
                //密文+SID_MAC
                case 5:
                    if (string.IsNullOrWhiteSpace(SendModule.SessionInitKey))
                    {
                        MessageBox.Show("请先建立应用连接");
                        return;
                    }
                    break;
                //明文
                case 0:
                //明文+RN
                case 1:
                default:

                    break;
            }
            await Task.Run(async () =>
            {
                while (AnalysisMessage.lastblock==0)
                {
                    await SendModule.ReadRequest(ReadMode.GetRequestNext, new List<string>() { AnalysisMessage.block.ToString("X4") }, MainViewModel.selectedDevice.DeviceAddress, SendModule.SecuritySelectedIndex);
                }
            });
        }
        public RelayCommand ReadCommand
        {
            get
            {
                return new RelayCommand(async () =>
                {
                    if (MainViewModel.selectedDevice == null)
                    {
                        MessageBox.Show("请选择设备");
                        return;
                    }
                    if (!MainViewModel.state)
                    {
                        MessageBox.Show("请先打开通道");
                        return;
                    }
                    //await ReadTask();
                    //await ReadNextTask();
                    await ReadTask().ContinueWith(async t => { await ReadNextTask(); });
                });
            }
        }

        public RelayCommand ExportCommand
        {
            get
            {
                return new RelayCommand(()=>{
                    try
                    {
                        using (var workbook = new XLWorkbook())
                        {
                            // 添加一个工作表
                            var worksheet = workbook.AddWorksheet("Sheet1");

                            // 设置标题行
                            worksheet.Row(1).Style.Font.Bold = true; // 标题字体加粗
                            worksheet.Row(1).Style.Fill.BackgroundColor = XLColor.AliceBlue; // 标题背景颜色
                            worksheet.Row(1).Style.NumberFormat.Format = "@";
                            // 添加标题

                            worksheet.Cell(1, 1).Value = "配置序号";
                            worksheet.Cell(1, 2).Value = "通信地址";
                            worksheet.Cell(1, 3).Value = "波特率";
                            worksheet.Cell(1, 4).Value = "规约类型";
                            worksheet.Cell(1, 5).Value = "端口";
                            worksheet.Cell(1, 6).Value = "通信密码";
                            worksheet.Cell(1, 7).Value = "费率个数";
                            worksheet.Cell(1, 8).Value = "用户类型";
                            worksheet.Cell(1, 9).Value = "接线方式";
                            worksheet.Cell(1, 10).Value = "额定电压";
                            worksheet.Cell(1, 11).Value = "额定电流";
                            worksheet.Cell(1, 12).Value = "采集器地址";
                            worksheet.Cell(1, 13).Value = "资产号";
                            worksheet.Cell(1, 14).Value = "PT";
                            worksheet.Cell(1, 15).Value = "CT";

                            // 设置单元格的格式为字符串

                            //添加内容
                            for (int i = 0; i < MeterInfoLIst.Count; i++)
                            {
                                worksheet.Row(i + 2).Style.NumberFormat.Format = "@";
                                MeterInfo meterInfo = MeterInfoLIst[i];
                                worksheet.Cell(i + 2, 1).Value = meterInfo.SeqNo.ToString();
                                worksheet.Cell(i + 2, 2).Value = meterInfo.CommuAddr;
                                worksheet.Cell(i + 2, 3).Value = meterInfo.Baudrate.ToString();
                                worksheet.Cell(i + 2, 4).Value = meterInfo.ProtocolType.ToString();
                                worksheet.Cell(i + 2, 5).Value = meterInfo.Port;
                                worksheet.Cell(i + 2, 6).Value = meterInfo.CommuCode;
                                worksheet.Cell(i + 2, 7).Value = meterInfo.TarriffNum;
                                worksheet.Cell(i + 2, 8).Value = meterInfo.UserType;
                                worksheet.Cell(i + 2, 9).Value = meterInfo.WireMode.ToString();
                                worksheet.Cell(i + 2, 10).Value = meterInfo.RatedVoltage;
                                worksheet.Cell(i + 2, 11).Value = meterInfo.RatedCurrent;
                                worksheet.Cell(i + 2, 12).Value = meterInfo.CollectAddr;
                                worksheet.Cell(i + 2, 13).Value = meterInfo.AssetNumber;
                                worksheet.Cell(i + 2, 14).Value = meterInfo.Pt;
                                worksheet.Cell(i + 2, 15).Value = meterInfo.Ct;
                            }
                            // 调整列宽以适应内容
                            worksheet.Columns().AdjustToContents();

                            // 保存工作簿
                            SaveFileDialog saveDialog = new SaveFileDialog
                            {
                                Filter = "Excel Workbook (*.xlsx)|*.xlsx|All Files (*.*)|*.*",
                                Title = "Save Excel File",
                                /*FileName= "电表档案"*/
                            };

                            if (saveDialog.ShowDialog() == true)
                            {
                                // 如果用户选择了路径，保存工作簿到该路径
                                workbook.SaveAs(saveDialog.FileName);
                                MessageBox.Show("保存成功");
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }
                });
            }
        }
    }
}
